package com.jiuxian.scheduling.util;

import okhttp3.*;
import org.apache.commons.collections.MapUtils;

import java.util.Map;

/**
 * Created by wangjingqing on 2017/12/26.
 * Http工具类<br>
 */
public class HttpUtil {

    static OkHttpClient httpClient = new OkHttpClient();

    /**
     * get请求方式<br>
     * @param url 请求路径
     * @return String
     */
    public static String get(String url) throws Exception{
        Request request = new Request.Builder().url(url).build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }

    /**
     * post表单提交<br>
     * @param url 请求路径
     * @param paras 请求参数
     * @return String
     * @throws Exception
     */
    public static String post(String url,Map<String,String> paras)throws Exception{
        FormBody.Builder builder = new FormBody.Builder();
        if(MapUtils.isNotEmpty(paras)){
            paras.forEach((key,value)->builder.add(key,value));
        }
        FormBody fromBody = builder.build();
        Request request = new Request.Builder().url(url)
                .addHeader("content-type", "text/html;charset:utf-8")
                .post(fromBody).build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }

    /**
     * JSON表单提交<br>
     * @param url 请求路径
     * @param json 请求参数
     * @return String
     * @throws Exception
     */
    public static String postJSON(String url,String json)throws Exception{
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }
}
